package org.example.mydeom.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.mydeom.common.MessageConstant;
import org.example.mydeom.common.RedisConstant;
import org.example.mydeom.pojo.entity.User;
import org.example.mydeom.service.impl.UserServiceImpl;
import org.example.mydeom.util.JwtTokenUtil;
import org.example.mydeom.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;


@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String jwt = request.getHeader(JwtTokenUtil.HEADER);
        log.info("token:{}",jwt);
        String username=null;
        Long userId=null;
        if(StringUtils.hasText(jwt)){
            try {
                JwtTokenUtil.validateJwtToken(jwt);
                username= JwtTokenUtil.getUserNameFromJwtToken(jwt);
                userId = JwtTokenUtil.getUserIdFromJwtToken(jwt);
                String token = (String)redisTemplate.opsForValue().get(RedisConstant.USER_TOKEN +userId);
                if(token== null|| token.isEmpty()){
                    log.error("Token已失效");
                    ResultUtil.Respond(MessageConstant.TOKEN_INVALID,"",0,response);
                    return;
                    //request.setAttribute("error", MessageConstant.TOKEN_INVALID);
                }
            }catch (Exception e){
                log.error("Token解析失败:{}",e.getMessage());
                request.setAttribute("error", MessageConstant.TOKEN_PARSING_FAILED);
            }
        }
        if(username!=null&& SecurityContextHolder.getContext().getAuthentication()==null){
            User user =(User) userService.loadUserByUsername(username);
             SecurityContextHolder.getContext()
                     .setAuthentication(
                             new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities())
                     );
        }
        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }

}
